package com.youshang.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 *  关于buffer的Scattering 和 Gathering
 * @author youshang
 * @date 2021/09/06 22:47
 **/
public class Test7 {

    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(8899);
        serverSocketChannel.socket().bind(inetSocketAddress);


        int messageLength = 9;
        ByteBuffer[] byteBuffers = new ByteBuffer[3];

        byteBuffers[0] = ByteBuffer.allocate(2);
        byteBuffers[1] = ByteBuffer.allocate(3);
        byteBuffers[2] = ByteBuffer.allocate(4);

        SocketChannel socketChannel = serverSocketChannel.accept();

        while (true){
            int byteRead = 0;
            while (byteRead < messageLength){
                long read = socketChannel.read(byteBuffers);
                byteRead += read;
                System.out.println("byteRead : "+ byteRead);
                Arrays.stream(byteBuffers).map(byteBuffer -> "position: "+ byteBuffer.position() + "  limit : "+ byteBuffer.limit()).forEach(s -> System.out.println("s = " + s));
            }
            //切换 读写
            Arrays.stream(byteBuffers).forEach(m -> m.flip());

            long bytesWritten = 0;
            while (bytesWritten < messageLength){
                long write = socketChannel.write(byteBuffers);
                bytesWritten += write;
            }

            // 使limit = capacity， position = 0
            Arrays.stream(byteBuffers).forEach(m -> m.clear());

            System.out.println("byteRead: "+ byteRead + "  byteWrite : "+ bytesWritten + "  messageLength : "+ messageLength);
        }
    }
}
